package neuron.library.ga.selection;

import java.util.Random;

import neuron.library.ga.AbstractGeneticMachine;
import neuron.library.ga.common.AbstractChromosome;
import neuron.library.ga.common.Population;

/*
 * This strategy plays to roulette with life of chromosomes.
 * Every chromosome have chance be alive proportional they fitness.
 */
public class RouletteSelection extends SelectionStrategy {

	public RouletteSelection(AbstractGeneticMachine gm) {
		super(gm);
	}

	@Override
	public void selection(Population population) {
		Random rand = new Random();
		float roulette = 0;
		float overall_score = 0;
		float current_score = 0;
		boolean brake_flag = false;
		AbstractChromosome unlucky_chromosome = null;
		
		population.calculateFitness();
		
		for (AbstractChromosome chromosome: population) {
			overall_score += 1.0/(float)chromosome.getScore();
		}
		
		while (population.size() > gm.getConfig().getPopulatonSize()) {
			current_score = 0;
			roulette = rand.nextFloat();
			brake_flag = false;
			for (AbstractChromosome chromosome: population) {
				current_score += 1.0/chromosome.getScore();
				if (current_score/overall_score > roulette) {
					unlucky_chromosome = chromosome;
					brake_flag = true;
				}
				if (brake_flag == true) {
					break;
				}
			}
			population.remove(unlucky_chromosome);
		}
	}

}
